package com.chhuang.ewcrm.config;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * 
* @ClassName: PropertiesUtil 
* @Description: 读取或写入项目中的资源配置文件Properties
* @author: 黄晨 
* @date: 2015-3-25
*
 */
public class PropertiesUtil {
	private PropertiesUtil(){}

	/**
	 * 根据文件名、键名获取值
	 * 注意:路径默认指向的是classpath的根目录
	 * @param propertiesFileName
	 * @param key
	 * @return
	 */
	public static String getValue(String propertiesFileName, String key) {
		PropertiesConfiguration config = getConfig(propertiesFileName);
		if(config!=null)
			return config.getString(key);
		else
			return null;
	}

	/**
	 * 根据文件名、键名获取值
	 * 注意:路径默认指向的是classpath的根目录
	 * @param propertiesFileName
	 * @param key
	 * @param def 默认值
	 * @return
	 */
	public static String getValue(String propertiesFileName, String key, String def) {
		PropertiesConfiguration config = getConfig(propertiesFileName);
		if(config!=null)
			return config.getString(key, def);
		else
			return def;
	}

	/**
	 * 根据文件名、键名设置值
	 * @param propertiesFileName
	 * @param key
	 * @param value
	 */
	public static void setValue(String propertiesFileName, String key, String value) {
		PropertiesConfiguration config = getConfig(propertiesFileName);
		if(config!=null){
			config.setProperty(key, value);
			try {
				OutputStreamWriter wirter = new OutputStreamWriter(
						new FileOutputStream(new File(propertiesFileName)), "UTF-8");
				config.write(wirter);
				wirter.close();
			} catch (ConfigurationException | IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取Configuration
	 * @param propertiesFileName
	 * @return
	 */
	private static PropertiesConfiguration getConfig(String propertiesFileName) {
		if(StringUtils.isEmpty(propertiesFileName)){
			return null;
		}

		Configurations configs = new Configurations();
		FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
		PropertiesConfiguration config = null;
		try {
			config = configs.properties(propertiesFileName);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}

		return config;
	}
}
